package com.msb.mall.product.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;
import com.msb.common.utils.R;
import com.msb.mall.product.dao.SkuInfoDao;
import com.msb.mall.product.entity.SkuImagesEntity;
import com.msb.mall.product.entity.SkuInfoEntity;
import com.msb.mall.product.entity.SpuInfoDescEntity;
import com.msb.mall.product.entity.vo.SeckillSkuRedisVo;
import com.msb.mall.product.entity.vo.SkuItemSaleAttrVo;
import com.msb.mall.product.entity.vo.SpuItemGroupAttrVo;
import com.msb.mall.product.entity.vo.SpuItemVo;
import com.msb.mall.product.feign.SeckillFeignServicce;
import com.msb.mall.product.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    AttrGroupService attrGroupService;
    @Autowired
    ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    SeckillFeignServicce seckillFeignServicce;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        //设置对应的检索条件
        //1.关键字查询
        String key = (String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            wrapper.and((w) -> {
                w.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        //分类
        String catalogId = (String) params.get("catalogId");
        if(StringUtils.isNotEmpty(catalogId) && !"0".equalsIgnoreCase(catalogId)){
            wrapper.eq("catalog_id", catalogId);
        }
        //品牌
        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id", brandId);
        }
        //价格区间
        String minPrice =  (String) params.get("min");
        if(StringUtils.isNotEmpty(minPrice)){
            wrapper.ge("price", minPrice);
        }
        String maxPrice =  (String) params.get("max");
        if(StringUtils.isNotEmpty(maxPrice)){
            try {
                BigDecimal bigDecimal = new BigDecimal(maxPrice);
                if(bigDecimal.compareTo(new BigDecimal(0)) > 0){
                    wrapper.le("price", maxPrice);
                }
            }catch (Exception e){
                log.error("最大价格转换异常");
            }
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public SpuItemVo item(Long skuId) throws ExecutionException, InterruptedException {

        SpuItemVo vo = new SpuItemVo();
        CompletableFuture<SkuInfoEntity> skuFuture = CompletableFuture.supplyAsync(() ->{
            //查询sku的基本信息
            SkuInfoEntity skuInfo = getById(skuId);
            vo.setSkuInfo(skuInfo);
            return skuInfo;
        },threadPoolExecutor);
        //thenAcceptAsync 即接收上一个阶段的结果但不返回新值的函数
        CompletableFuture<Void> saleFuture = skuFuture.thenAcceptAsync((res) -> {
            //获取sku中的销售属性的组合
            List<SkuItemSaleAttrVo> saleAttrs = skuSaleAttrValueService.getSaleValuesWithSkuId(res.getSkuId());
            vo.setSaleAttrs(saleAttrs);
        }, threadPoolExecutor);

        CompletableFuture<Void> descFuture = skuFuture.thenAcceptAsync((res) ->{
            //获取spu的介绍
            SpuInfoDescEntity desc = spuInfoDescService.getById(res.getSpuId());
            vo.setDesc(desc);
        },threadPoolExecutor);



        CompletableFuture<Void> spuFuture =  skuFuture.thenAcceptAsync((res) ->{
            //获取spu的规格参数
            //根据spu编号和catalogId编号查询所有的属性及其属性信息
            List<SpuItemGroupAttrVo> itemGroupAttrVo =  attrGroupService.getAttrGroupWithSpuId(res.getSpuId(),res.getCatalogId());
            vo.setBaseAttr(itemGroupAttrVo);
        },threadPoolExecutor);

        CompletableFuture<Void> imageFuture =  CompletableFuture.runAsync(() ->{
            //sku的图片信息
            List<SkuImagesEntity> skuImages = skuImagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id",skuId));
            vo.setSkuImages(skuImages);
        },threadPoolExecutor);


        CompletableFuture<Void> seckillFuture =  CompletableFuture.runAsync(() ->{
            //查询商品的秒杀活动
            R r = seckillFeignServicce.getSeckillSessionBySkuId(skuId);
            if(r.getCode() == 0){
                String  o = (String) r.get("data");
                SeckillSkuRedisVo seckillSkuRedisVo = JSON.parseObject(o, SeckillSkuRedisVo.class);
                vo.setSeckillVO(seckillSkuRedisVo);
            }
        },threadPoolExecutor);

        CompletableFuture.allOf(saleFuture,descFuture,spuFuture,imageFuture,seckillFuture).get();
        return vo;
    }



}
